package internal

import (
	"math"
	"math/rand"
)

func HorseRand_Yuan(sortParams []int64) []ItemList {
	min := 0.06 // 赛道时间差
	max := 0.06
	tDifference := 0.05 // 速度差值
	randomValue := 0.0  // 时间随机差值
	lostTimeValue := 30.0
	numPartitionsOptions := []int{4, 6, 8, 10} // 路程切割为双数
	var data []ItemList
	data = make([]ItemList, 10)

	for i := len(sortParams) - 1; i >= 0; i-- {
		randomIndex := rand.Intn(len(numPartitionsOptions))
		randomInteger := numPartitionsOptions[randomIndex]

		if i < len(sortParams)-1 {
			randomValue = rand.Float64()*(max-min) + min
		}

		result := lostTimeValue - randomValue
		lostTimeValue = math.Round(result*100) / 100

		horses := DistributeNumbers(lostTimeValue, randomInteger, tDifference)
		data[i].items = append(data[i].items, horses...)
	}
	//arrHore := make([][]HorseData, len(sortParams))
	var arrHore []ItemList
	arrHore = make([]ItemList, 10)
	for i := 0; i < len(sortParams); i++ {
		arrHore[sortParams[i]-1] = data[i]
	}

	return arrHore
}

func DistributeNumbers(targetSum float64, numParts int, tDifference float64) []Item {
	// 计算平均数
	average := float32(targetSum / float64(numParts))

	// 初始化一个数组来存储每份的数值
	//values := make([]HorseData, numParts)
	var values []Item
	// 初始化数值之和
	var sum float64

	// 分配数值
	for i := 0; i < numParts; i++ {
		randomOffset := float32(rand.Float64()*(2*tDifference) - tDifference)

		partValue := float64(math.Floor(float64(average*100+randomOffset*100)) / 100)

		// 将数值添加到数组中
		//values[i] = Item{t: partValue, s: 0}
		values = append(values, Item{
			s: 0,
			t: partValue,
		})
		// 更新数值之和
		sum += float64(partValue)
	}

	// 调整数值，直到数值之和等于目标值
	//fmt.Println(targetSum)
	adjustment := targetSum*100 - sum*100
	result := values[0].t*100 + adjustment
	values[0].t = math.Round(result) / 100
	//fmt.Println(values)
	return values
}

//func main() {
//	// Example sortParamsP
//	sortParams := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
//
//	result := HorseRand(sortParams)
//
//	// Print the result
//	totle := []float64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
//	for i, arr := range result {
//		for j, horse := range arr {
//			totle[i] += horse.T
//			fmt.Printf("  Horse %d: t=%.1f\n", j+1, horse.T)
//		}
//	}
//}
